package cn.turboinfo.fuyang.api.domain.common.handler.order;


import cn.turboinfo.fuyang.api.domain.common.service.company.HousekeepingCompanyService;
import cn.turboinfo.fuyang.api.domain.util.PhoneUtils;
import cn.turboinfo.fuyang.api.domain.util.SecurityUtils;
import cn.turboinfo.fuyang.api.domain.util.UsernameUtils;
import cn.turboinfo.fuyang.api.entity.common.pojo.company.HousekeepingCompany;
import cn.turboinfo.fuyang.api.entity.common.pojo.order.ServiceOrder;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;

@RequiredArgsConstructor
@Component
public class ServiceOrderDataFactory {

    @Value("${kit.security.rsa.public-key:}")
    private String base64RSAPublicKey;

    private final HousekeepingCompanyService housekeepingCompanyService;

    public void assembleCompany(List<ServiceOrder> serviceOrderList) {

        Set<Long> companyIdSet = serviceOrderList.stream()
                .map(ServiceOrder::getCompanyId)
                .collect(Collectors.toSet());

        Map<Long, HousekeepingCompany> companyMap = housekeepingCompanyService.findByIdCollection(companyIdSet)
                .stream()
                .collect(Collectors.toMap(HousekeepingCompany::getId, Function.identity()));

        serviceOrderList.forEach(it -> {
            if (companyMap.containsKey(it.getCompanyId())) {
                it.setCompanyName(companyMap.get(it.getCompanyId()).getName());
            }
        });
    }


    public void maskInfo(List<ServiceOrder> serviceOrderList) {
        serviceOrderList.stream()
                .peek(this::maskInfo)
                .toList();
    }

    public ServiceOrder maskInfo(ServiceOrder serviceOrder) {
        serviceOrder.setMobileEncrypt(SecurityUtils.encodeBase64(SecurityUtils.encryptRSA(serviceOrder.getMobile().getBytes(), SecurityUtils.decodeBase64(base64RSAPublicKey))));
        serviceOrder.setMobile(PhoneUtils.maskPhoneNum(serviceOrder.getMobile()));
        serviceOrder.setContact(UsernameUtils.maskUsername(serviceOrder.getContact()));
        return serviceOrder;
    }
}
